package com.hbnu.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 需求：使用PreparedStatement进行数据库的CRUD操作
 *
 * @author kittychen
 * @since 2025-10-22 14:21
 */
public class JdbcDemo05 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            InputStream resourceAsStream = JdbcDemo05.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);

            String driver = properties.getProperty("driver");
            String url = properties.getProperty("url");
            String user = properties.getProperty("username");
            String password = properties.getProperty("password");
            Class.forName(driver);

            connection = DriverManager.getConnection(url, user, password);

            // 自己独立完成修改、删除、查询等操作
            String sql = "insert into tb_user values(?, ?, ?, ?)";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 4);
            preparedStatement.setString(2, "kitty");
            preparedStatement.setString(3, "123456");
            preparedStatement.setDouble(4, 1000.0);
            int rows = preparedStatement.executeUpdate();
            System.out.println(rows == 1 ? "插入成功" : "插入失败");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
